/*
 * @Author: yangzonglong
 * @Date: 2021-03-01 13:18:46
 * @version: v1.0.0
 * @Descripttion:
 * @LastEditors: Please set LastEditors
 * @LastEditTime: 2021-08-17 10:35:27
 * @Auditor:
 */
import React, { useCallback, useState, useEffect, useMemo } from 'react';
import { ActionText, BtnUpload } from '@library';
import { Upload, message } from 'antd';
import { UploadChangeParam } from 'antd/lib/upload';
import evalScriptText from './../../../eval';
import MIME from '@library/components/fileUpload/mime';
// import { DEFAULT_ACCEPT } from '@library/components/fileUpload/FileUpload';
import { fileDataSource } from './UploadController';

const T = window.$app.t;
interface Props {
  onlyShowList?: boolean;
  onChange?:
  (f: any[]) => void;
  options?: {
    accept?: string;
    maxCount?: number;
    uploadUrl?: string;
    downloadUrl: string;
    downloadScript?: string;
  };
  value?: any[];
  scriptsChangeData?: object;
  record?: Record<string, any>;
  enviromentConfig?: any;
}

const DEFAULT_ACCEPT = fileDataSource.join(',');

const App = (props: Props) => {

  const { onChange, options, value, onlyShowList } = props;

  const [fileList, setFileList] = useState<any[]>([]);

  useEffect(() => {
    setFileList(value || []);
  }, [value]);

  const mimeTypes = useMemo(() => {
    const accept = (options?.accept || DEFAULT_ACCEPT).split(',');
    return accept.map(item => MIME[item]).flat();
  }, [options?.accept]);

  const beforeUpload = useCallback(
    (file, fileList) => {
      if (!options?.maxCount && !mimeTypes.length) return true; // 未限制体积未限制数量 允许上传

      if (options?.maxCount && options.maxCount === fileList.length - 1) {
        message.warning(`总数量不能超过${options.maxCount}`);
        return Upload.LIST_IGNORE;
      }

      if (file.type && !mimeTypes.includes(file.type)) {
        message.warning('格式不支持');
        return Upload.LIST_IGNORE;
      }
      return true;
    },
    [options, mimeTypes]
  );

  const deleteFile = useCallback(async (param: any) => {
    onChange?.(fileList.filter(item => item.uid !== param.uid));
  }, [fileList, onChange]);

  const changeFiles = useCallback((f: UploadChangeParam) => {
    onChange?.(f.fileList);
  }, [onChange]);

  const previewFile = (file: any) => {
    if (props.options?.downloadScript) {
      evalScriptText({
        scriptText: props.options?.downloadScript,
        extra: {
          _OBJ1_: props.scriptsChangeData,
          _ENV_: props.enviromentConfig || {},
          _RECORD_: props.record,
          _OBJ_: file
        },
        next: () => { }
      });
    } else {
      window.open(file.url);
    }
  };

  return (
    <BtnUpload
      downloadUrl={props.options?.downloadUrl}
      onPreview={previewFile}
      action={props.options?.uploadUrl}
      onlyShowList={onlyShowList || props?.record?.onlyShowList}
      fileList={fileList}
      beforeUpload={beforeUpload}
      targetNode={
        <ActionText
          type={
            onlyShowList || props?.record?.onlyShowList
              ? `${T('total')}${fileList?.length || 0}${T('gfj')}`
              : fileList?.length
                ? fileList?.length >= 2
                  ? `${T('total')}${fileList?.length || 0}${T('gfj')}`
                  : fileList[0]?.name || fileList[0]?.response?.originalname || fileList[0]?.fileName
                : T('upload')
          }
        />
      }
      onChange={changeFiles}
      accept={options?.accept || DEFAULT_ACCEPT}
      onDelete={deleteFile}
    />
  );
};

export default App;
